<template>
  <el-container style="display: flex">
    <el-header style="height: 40px;">
      <div style="text-align: left;font-weight: bold">检查预约信息</div>
    </el-header>

    <div v-show="!isCanceled">
      <el-card shadow="none" style="border:none;text-align: left;padding-left: 100px;padding-right: 100px;">
        <p>就诊日期：{{ examInfo.date }}</p>
        <p>就诊时段：{{ examInfo.timeSlot }}</p>
        <p>就诊科室：{{ examInfo.departmentName }}</p>
        <p>就诊门诊：{{ examInfo.clinicName }}</p>
        <p>检查项目：{{ examInfo.examItemName }}</p>
        <p>医生姓名：{{ examInfo.checkDoctorName }}</p>
<!--        <p>医生职称：{{ examInfo.doctorTitle }}</p>-->
        <p>患者姓名：{{ examInfo.patientName }}</p>
        <p>就诊卡号：{{ examInfo.medicalCard }}</p>
        <p>挂号费用：{{ examInfo.fee }}</p>
        <p v-show="isPaid">挂号时间：{{ formatDateTime(currentRecord.payTime) }}</p>
        <p v-show="isPaid">挂号单号：{{ currentRecord.orderId }}</p>
      </el-card>

      <div style="text-align: left;background-color: rgba(65, 159, 255, 0.08);margin-top:20px;padding: 1px 20px 10px 20px;">
        <h4>注意事项</h4>
        <p style="color: #ff1e00">{{ examItem.attentions }}</p>

      </div>
    </div>

    <el-footer style="margin-top: 30px;display: flex; justify-content: center; align-items: center;">
      <el-button v-show="!isPaid" type="primary" @click="payConfirm">立即支付</el-button>
      <el-button v-show="isPaid && !isCanceled" type="warning" plain @click="cancelAppointVisible = true">取消预约</el-button>
      <el-button v-show="isPaid && !isCanceled" type="primary" @click="router.push({name:'Home'})">返回首页</el-button>
      <div v-show="isCanceled" style="display: flex;flex-direction: column;align-items: center;">
        <el-text  style="margin-bottom: 15px;color: #ff1e00">您已取消预约</el-text>
        <el-button type="primary" plain @click="router.push({name:'Home'})">返回首页</el-button>
      </div>
    </el-footer>

    <!--支付dialog-->
    <el-dialog
        v-model="payDialogVisible"
        width="500"
        center
    >
      <span>是否已完成支付？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="getPayRecord">已支付</el-button>
          <el-button  type="warning" @click="payDialogVisible = false">取消支付</el-button>
        </div>
      </template>
    </el-dialog>

    <!--取消预约dialog-->
    <el-dialog
        v-model="cancelAppointVisible"
        width="500"
        center
    >
      <span>是否取消支付？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancelConfirm">确认取消</el-button>
          <el-button  @click="cancelAppointVisible = false">关闭取消</el-button>
        </div>
      </template>
    </el-dialog>

  </el-container>
</template>

<script setup>
import { ref} from "vue";
import mitt from '@/utils/mitt';
import alipayApi from "@/apis/alipay";
import examRecordApi from "@/apis/examRecord";
import { ElMessage } from "element-plus";
import {useRouter} from "vue-router";
import departClinicDoctorItemApi from "@/apis/departClinicDoctorItem";


const emitter = mitt;
const router = useRouter();

const examInfo = JSON.parse(sessionStorage.getItem('examInfo'))
const payDialogVisible = ref(false)
const orderId = ref('')
const examItem = ref('')
const getExamItemDetail = async () =>{
  const data = {
    id:examInfo.examItemId
  }
  examItem.value = (await departClinicDoctorItemApi.getExamItemDetail(data)).data
}
getExamItemDetail()
/**
 * 立即支付
 */
const payConfirm = () =>{
  payDialogVisible.value = true;
  payMethod();
}


/**
 * 支付调用
 */
const payMethod = async () =>{
  const data = {
    patientId:examInfo.patientId,
    departmentId:examInfo.departmentId,
    clinicId:examInfo.clinicId,
    doctorId:examInfo.checkDoctorId,
    date:examInfo.date,
    timeSlot:examInfo.timeSlotId,
    fee:examInfo.fee,
    examRecordId:examInfo.examRecordId,
    examSpotsId:examInfo.examSpotsId
  }
  console.log(data)
  const res = await alipayApi.pay(data)
  orderId.value = res.data.orderId;

  const div = document.createElement("div");
  div.innerHTML = res.data.payPage; // data就是接口返回的form 表单字符串
  document.body.appendChild(div);
  document.forms[0].setAttribute("target", "_blank"); // 新开窗口跳转
  document.forms[0].submit();

}

const isPaid = ref(false);
const currentRecord = ref('')

/**
 * 支付状态获取
 */
const getPayRecord = async () =>{
  const data = {
    orderId:orderId.value,
    patientId:examInfo.patientId
  }
  // console.log(data)
  const res = await examRecordApi.getExamCurrentRecord(data)
  console.log(res)
  currentRecord.value = res.data;

  if(res.code === 200){
    ElMessage({
      title:'成功提示',
      message:'支付成功',
      type:'success'
    })
    isPaid.value = true;
    emitter.emit('next', 5);
    payDialogVisible.value = false;
  }else {
    ElMessage({
      title:'失败提示',
      message:'支付失败',
      type:'error'
    })
  }

}

/**
 * 时间格式
 * @param date
 * @returns {string}
 */
function formatDateTime(payTime) {
  const date = new Date(payTime);
  const year = date.getFullYear(); // 获取年份
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 获取月份，月份从0开始，所以加1
  const day = date.getDate().toString().padStart(2, '0'); // 获取日
  const hours = date.getHours().toString().padStart(2, '0'); // 获取小时
  const minutes = date.getMinutes().toString().padStart(2, '0'); // 获取分钟
  const seconds = date.getSeconds().toString().padStart(2, '0'); // 获取秒

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const isCanceled = ref(false);

/**
 * 取消预约 -退款 -还号
 */
const cancelAppointVisible = ref(false)

const cancelConfirm = async () =>{
  const data = {
    orderId:orderId.value,
    fee:examInfo.fee,
    examSpotsId:examInfo.regSpotsId,
    examRecordId:currentRecord.value.id
  }
  // console.log(data)
  const res = await alipayApi.refund(data);
  if(res){
    cancelAppointVisible.value = false;
    ElMessage({
      title:'成功提示',
      message:'取消预约成功，挂号金额已退还',
      type:'success'
    })
    isCanceled.value = true;
  }else {
    ElMessage({
      title:'失败提示',
      message:'取消预约失败',
      type:'error'
    })
    cancelAppointVisible.value = false;
  }
  sessionStorage.removeItem('examInfo')
}


</script>



<style scoped>

</style>
